package com.gcloud.googledrive;

import java.io.File;
import java.io.IOException;
import com.example.gcode.Archivos;
import com.example.gcode.GCloudSingleton;
import com.example.gcode.R;
import com.gcloud.googledrive.UploadGoogleFile;
import com.gfilechooser.utils.FileUtils;
import com.google.api.client.extensions.android.http.AndroidHttp;
import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.drive.Drive;
import com.google.api.services.drive.DriveScopes;
import com.utils.Message;
import android.accounts.AccountManager;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.Toast;

public class DeleteGoogleFileActivity extends Activity {
	private ProgressDialog pDialog;
	Drive service;
	GoogleAccountCredential credential;
	private static final int REQUEST_ACCOUNT = 1;
	private static final int REQUEST_CODE = 100;
	private static final int REQUEST_RETURN = 101;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.archivos_list);
		credential = GoogleAccountCredential.usingOAuth2(this,
				DriveScopes.DRIVE);
		// credential.setSelectedAccountName("guilletec@gmail.com");
		// service = getDriveServices(credential);
		// new CargarArchivos().execute();
		startActivityForResult(credential.newChooseAccountIntent(),
				REQUEST_ACCOUNT);
	}

	private void showChooser() {
		Intent target = FileUtils.createGetContentIntent();
		Intent intent = Intent.createChooser(target,
				getString(R.string.chooser_title));
		try {
			startActivityForResult(intent, REQUEST_CODE);
		} catch (ActivityNotFoundException e) {
			Log.i("showChooser", e.getLocalizedMessage());
		}
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Log.i("jalskjdf", "guaro!!");
		switch (item.getItemId()) {
		case R.id.menu_upload:

			Log.i("here", "upload");
			showChooser();
			break;
		case R.id.menu_download:
			Log.i("here", "download");
			break;
		case R.id.menu_delete:
			Log.i("here", "delete");
			break;
		case R.id.menu_bookmark:
			Log.i("here", "bookmark");
			break;
		case R.id.menu_save:
			Log.i("here", "save");
			break;
		case R.id.menu_search:
			Log.i("here", "search");
			break;
		case R.id.menu_google_drive:
			Log.i("here", "google drive");
			break;
		case R.id.menu_dropbox:
			Log.i("here", "dropbox");
			break;
		}
		return true;
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// TODO Auto-generated method stub
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.layout.menu_layout, menu);
		return true;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_ACCOUNT:
			Log.i("Google Drive Sync", "REQUEST_ACCOUNT");
			if (resultCode == RESULT_OK && data != null
					&& data.getExtras() != null) {

				Log.i("Google Drive Sync", "Todo salio bien");
				String accountName = data
						.getStringExtra(AccountManager.KEY_ACCOUNT_NAME);
				Log.i("on activity result: ", accountName);
				credential.setSelectedAccountName(accountName);
				service = getDriveServices(credential);

				new CargarArchivos().execute();
			}
			break;
		case REQUEST_CODE:
			if (resultCode == RESULT_OK) {
				if (data != null) {
					final Uri uri = data.getData();
					try {
						final File file = FileUtils.getFile(uri);
						showToast("File selected: " + file.getAbsolutePath());
						UploadGoogleFile googleFile = new UploadGoogleFile(
								service, DeleteGoogleFileActivity.this, file);
						googleFile.execute();
					} catch (Exception e) {
						Log.e("FileSelectorTestActivity", "File select error",
								e);
					}
				}
			}
			break;
		case REQUEST_RETURN:
			Log.i("Google Drive Sync", "REQUEST_RETURN");
			new CargarArchivos().execute();
			break;
		}
	}

	private Drive getDriveServices(GoogleAccountCredential credential) {
		return new Drive.Builder(AndroidHttp.newCompatibleTransport(),
				new GsonFactory(), credential).build();
	}

	public void showToast(final String toast) {
		runOnUiThread(new Runnable() {
			@Override
			public void run() {
				Toast.makeText(getApplicationContext(), toast,
						Toast.LENGTH_SHORT).show();
			}
		});
	}

	class CargarArchivos extends AsyncTask<String, String, String> {

		/**
		 * Before starting background thread Show Progress Dialog
		 * */
		@Override
		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(DeleteGoogleFileActivity.this);
			pDialog.setMessage(Message.CHARGING_FILES);
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		GCloudSingleton gCloudSingleton;

		/**
		 * getting Inbox JSON
		 * */
		protected String doInBackground(String... params) {
			String fileId = params[0];
			Log.i("GCLOUD", "Ya entre a doInBackground for delete :)");
			try {
				service.files().delete(fileId).execute();
				Log.i("fileDeleted()", fileId);
			} catch (IOException e) {
				Log.i("fileDeleted error()",
						"something goes really wrong deleting file ");
			}
			Log.i("retrieveAllFiles()", "to execute delete Files");
			return "true";
		}

		/**
		 * After completing background task Dismiss the progress dialog
		 * **/
		protected void onPostExecute(String file_url) {
			pDialog.dismiss();
			if (file_url.equalsIgnoreCase("true")) {
				Intent newIntent = new Intent(DeleteGoogleFileActivity.this,
						Archivos.class);
				startActivity(newIntent);
			} else {
				Log.i("OnPostExecute", "something goes wrong");
				startActivityForResult(credential.newChooseAccountIntent(),
						REQUEST_ACCOUNT);
			}
		}

	}
}
